<template>
  <view>
    <!-- 搜索框 -->
    <YgSearch></YgSearch>

    <!-- tab栏 -->
    <u-tabs
      :list="list"
      :is-scroll="false"
      :current="current"
      @change="change"
      active-color="#eb4450"
      bar-width="180"
    ></u-tabs>
    <!-- 商品列表的内容 -->
    <view v-if="current == 0" class="goods-content">
      <navigator
        class="goods-item u-flex u-margin-bottom-10"
        v-for="item in goods"
        :key="item.goods_id"
        :url="'/pages/goods_detail/goods_detail?id=' + item.goods_id"
      >
        <view class="goods-img u-flex-1">
          <u-image :src="item.goods_small_logo" mode="widthFix"></u-image>
        </view>

        <view class="goods-info u-flex-2">
          <view class="goods-name u-line-2">{{ item.goods_name }}</view>
          <view class="goods-price">¥{{ item.goods_price }}</view>
        </view>
      </navigator>
    </view>
    <view v-else-if="current == 1" class="goods-content">销量</view>
    <view v-else class="goods-content">价格</view>
  </view>
</template>

<script>
//全局变量请求参数
const params = {
  query: "", // 关键字
  cid: "", //分类id
  pagenum: 1, //页码
  pagesize: 10, //页容量
};

//全局变量 总页数
let totalPages = 1;

export default {
  data() {
    return {
      goods: [], //申请回来的数据

      list: [
        {
          name: "综合",
        },
        {
          name: "销量",
        },
        {
          name: "价格",
        },
      ],
      current: 0,
    };
  },

  methods: {
    change(index) {
      this.current = index;
    },
    //发送请求获取商品列表数据
    async getGoods(callback) {
      const res = await this.$u.get("/goods/search", params);
      //   this.goods = res.message.goods;

      //分页数组 叠加 （新旧的数组拼接在一起 数组合并）
      this.goods = [...this.goods, ...res.message.goods];
      //计算总页数
      totalPages = Math.ceil(res.message.total / params.pagesize);

      //等待数回来 关闭页面的下拉刷新
      callback && callback();
    },
    async onLoad(option) {
      // console.log();
      const { id } = option;
      // const res = await this.$u.get("/goods/search", { cid: id });
      // this.goods = res.message.goods;
      params.cid = id;
      this.getGoods();
    },
  },
  //滚动条触底
  onReachBottom() {
    //判断有没有下一页
    if (params.pagenum >= totalPages) {
      uni.showToast({
        title: "没有更多数据了",
        icon: "none",
      });
    } else {
      //页面递增
      params.pagenum++;
      this.getGoods();
    }
  },
  //下拉刷新事件
  onPullDownRefresh() {
    //清空数据
    this.goods = [];
    //重置页码
    params.pagenum = 1;
    this.getGoods(function () {
      //等待数据回来 关闭页面的下拉刷新
      uni.stopPullDownRefresh();
    });
  },
};
</script>


<style lang="scss">
.goods-item {
  // 设置子项拉伸到父项的高度
  align-items: stretch;

  border-bottom: 1rpx solid #eee;
}
.goods-info {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  .goods-price {
    color: $themeColor;
  }
}
</style>